/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sv.com.intesal.clases;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;

import java.util.HashMap;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import sv.com.intesal.conexion.cConexion;
import sv.com.intesal.reporte.controlador.GenerarReporte;

//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
/**
 *
 * @author ejerez
 */
public class XMLReporte {

    private String eRoot;

    public XMLReporte() {
        this.eRoot = "";
    }

    public XMLReporte(String root) {
        this.eRoot = root;
    }

    private ResultSet getResultSet_from_SQL(String sql) throws Exception {
        try {
            return cConexion.conectar().prepareStatement(sql).executeQuery();
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public void Element_XML(String sql) throws Exception {

        try {
            ResultSet rs = this.getResultSet_from_SQL(sql);
            Element root = null;
            Element eRegistro = null;
            Element eChild = null;

            if (this.eRoot.equals("")) {
                root = this.crearNuevoElemento("Reporte");
            } else {
                root = this.crearNuevoElemento(this.eRoot);
            }

            Integer columnCount = rs.getMetaData().getColumnCount();
            String columnName[] = new String[columnCount + 1];
            String columnType[] = new String[columnCount + 1];

            for (int i = 1; i <= columnCount; i++) {
                columnName[i] = rs.getMetaData().getColumnName(i);
                columnType[i] = rs.getMetaData().getColumnTypeName(i);
                //System.out.println("columnName[i]: " + columnName[i] + ", " + "columnType[i]: " + columnType[i]);
            }

            while (rs.next()) {
                eRegistro = this.crearNuevoElemento("REGISTRO");
                for (int i = 1; i <= columnCount; i++) {
                    eChild = this.crearNuevoElemento(columnName[i].toString());

                    if (rs.getString(columnName[i].toString()) != null) {
                        this.agregarElementoHijo(eRegistro, eChild, rs.getString(columnName[i].toString()));
                    } else {
                        this.agregarElementoHijo(eRegistro, eChild, "");
                    }
                }
                this.agregarElementoHijo(root, eRegistro);
            }
            Document document = crearDocumentXml(root);
            String xmlResultante = PasarXmlString(document);
            System.out.println("xmlResultante: " + xmlResultante);

            /*AJM- Test
            Map reportParams = new HashMap();
            reportParams.put("Condicion", "su.id_su = m.id_su and m.id_m = ms.id_m and su.id_su=2");
            GenerarReporte gr = new GenerarReporte();
            String directorioReporte = "/reportes/testXML.jasper";
            System.out.println("before going to Reporte");
            gr.generateReport(reportParams, directorioReporte, xmlResultante);

            /*End Test*/

        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public void Element_XML(ResultSet rs) throws Exception {

        try {
            Element root = null;
            if (this.eRoot.equals("")) {
                root = this.crearNuevoElemento("Reporte");
            } else {
                root = this.crearNuevoElemento(this.eRoot);
            }

            Element eRegistro = null;
            Element eChild = null;

            Integer columnCount = rs.getMetaData().getColumnCount();
            String columnName[] = new String[columnCount + 1];
            String columnType[] = new String[columnCount + 1];

            for (int i = 1; i <= columnCount; i++) {
                columnName[i] = rs.getMetaData().getColumnName(i);
                columnType[i] = rs.getMetaData().getColumnTypeName(i);
                //System.out.println("columnName[i]: " + columnName[i] + ", " + "columnType[i]: " + columnType[i]);
            }

            while (rs.next()) {
                eRegistro = this.crearNuevoElemento("REGISTRO");
                for (int i = 1; i <= columnCount; i++) {
                    eChild = this.crearNuevoElemento(columnName[i].toString());

                    if (rs.getString(columnName[i].toString()) != null) {
                        this.agregarElementoHijo(eRegistro, eChild, rs.getString(columnName[i].toString()));
                    } else {
                        this.agregarElementoHijo(eRegistro, eChild, "");
                    }
                }
                this.agregarElementoHijo(root, eRegistro);
            }
            Document document = crearDocumentXml(root);
            String xmlResultante = PasarXmlString(document);
            System.out.println("xmlResultante: " + xmlResultante);

            /*AJM- Test
            Map reportParams = new HashMap();
            reportParams.put("Condicion", "su.id_su = m.id_su and m.id_m = ms.id_m and su.id_su=2");
            GenerarReporte gr = new GenerarReporte();
            String directorioReporte = "/reportes/testXML.jasper";
            System.out.println("before going to Reporte");
            gr.generateReport(reportParams, directorioReporte, xmlResultante);

            /*End Test*/
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public void makeByteArray(Element el) throws Exception {
        try {
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public Element agregarElementoHijo(Element padre, Element hijo, String var_text) throws Exception {
        try {
            var_text = var_text.replaceAll("&", "&amp;");
            var_text = var_text.replaceAll("<", "&lt;");
            var_text = var_text.replaceAll(">", "&gt;");
            var_text = var_text.replaceAll("\'", "&quot;");
            var_text = var_text.replaceAll("\"", "&apos;");
            hijo.setText(var_text);
            padre.addContent(hijo);
            return padre;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public Element agregarElementoHijo(Element padre, Element hijo) throws Exception {
        try {
            padre.addContent(hijo);
            return padre;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public Element agregarAtributo(Element p_CElemento, String p_strNombre, String p_strValor) throws Exception {
        try {
            p_CElemento.setAttribute(p_strNombre, p_strValor);
            return p_CElemento;
        } catch (Exception e) {
            throw new Exception(e);
        }

    }

    public Element crearNuevoElemento(String var_text) throws Exception {
        try {
            Element nuevo = new Element(var_text);
            return nuevo;
        } catch (Exception e) {
            throw new Exception(e);
        }

    }

    public Document crearDocumentXml(Element root) throws Exception {
        try {
            Document nuevo = new Document(root);
            return nuevo;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public String PasarXmlString(Document p_DocumentoXML) {
        Format f = null;

        XMLOutputter outputter = new XMLOutputter();
        String cadenaXml = outputter.outputString(p_DocumentoXML);


        FileWriter writer;
        try {
            writer = new FileWriter("C:/Programas EJ/myFile.xml");
            //writer = new FileWriter("/home/jm/myFile.xml");
            outputter.output(p_DocumentoXML, writer);
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(XMLReporte.class.getName()).log(Level.SEVERE, null, ex);
        }

        return cadenaXml;
    }
}
